package com.zxy.lagouzuoye;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author zhangxuyuan
 * @version 1.0
 * @date 2020/10/24
 */
public class ProxyFactory {
    public static Object getCglibProxy(final Object obj) {
        return  Enhancer.create(obj.getClass(), new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                //判断是否被transaction修饰
                if(method.isAnnotationPresent(Transaction.class))
                {   //被注解修饰过
                    System.out.println("事务前");
                    result = method.invoke(obj,objects);
                    System.out.println("事务后");
                }
                else
                {   //未被注解修饰
                    result = method.invoke(obj,objects);
                }

                return result;
            }
        });
    }
}
